//
//  GroupHeaderView.m
//  Guazi
//
//  Created by koolearn on 11-5-8.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GroupHeaderView.h"
#import "ContactsViewController.h"
#import "GuaziAppDelegate.h"
#import "GroupDetailViewController.h"
#import "PopMenuViewController.h"
#import "MessagePicker.h"
#import "GroupAddViewController.h"
#import "GroupUserListViewController.h"
#import "GroupService.h"

#define kMenuItemNameTwitter @"组内分享"
#define kMenuItemNameDM @"群发消息"
#define kMenuItemNameMessage @"群发短信"
#define kMenuItemNameMember @"设置组成员"
#define kMenuItemNameEdit @"修改分组"
#define kMenuItemNameDelete @"删除分组"


@interface GroupHeaderView(private)
- (void) setOperationStatus;
- (NSArray*) menuItemNames;
- (void) postTweet;
- (void) postDirectMessage;
- (void) sendMessage;
- (void) editGroup;
- (void) member;
- (void) deleteGroup;
@end

@implementation GroupHeaderView

@synthesize group;
@synthesize section;
@synthesize openFlagImage;
@synthesize popoverController;

#pragma mark - 生命周期方法

- (id)initWithFrame:(CGRect)frame group:(FriendGroup*)agroup section:(NSInteger)sec
{
    self = [super initWithFrame:frame];
    if ( self ) {
		self.group = agroup;
		self.section = sec;
		
		UIImage* image = [[UIImage imageNamed:@"con_group.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:5];
		self.backgroundColor = [UIColor colorWithPatternImage:image];
		
		CGRect frame = CGRectMake(6, 6, 18, 18);
		UIImageView* imageView = [[UIImageView alloc] initWithFrame:frame];
		imageView.backgroundColor = [UIColor clearColor];
        
        if ( group.expanded ) {
            imageView.image = [UIImage imageNamed:@"group_open.png"];
        }
        else {
            imageView.image = [UIImage imageNamed:@"group_close.png"];
        }
		
		self.openFlagImage = imageView;
		[self addSubview:self.openFlagImage];
		[imageView release];
		
        UILabel* nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 250, 30)];
		nameLabel.backgroundColor = [UIColor clearColor];
        nameLabel.font = [UIFont systemFontOfSize:13];
		nameLabel.textColor = [UIColor colorWithRed:0 green:0.5f blue:0.71f alpha:1.0f];
		nameLabel.text = [NSString stringWithFormat:@"%@ (%d)",group.name, [group.friends count]];
		[self addSubview:nameLabel];
		[nameLabel release];
        
        if ( group.expanded && group.groupId >= 0 ) {
			menuButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
            [menuButton setImage:[UIImage imageNamed:@"group_button.png"] forState:UIControlStateNormal];
			menuButton.frame = CGRectMake(265, 4, 25, 25);
			[menuButton addTarget:self action:@selector(popMenu) forControlEvents:UIControlEventTouchUpInside];
			[self addSubview:menuButton];
        }
		
		[self addTarget:self action:@selector(expandSection) forControlEvents:UIControlEventTouchDown];
		
        [self setOperationStatus];
    }
    return self;
}


- (void)dealloc {
	[group release];
    [menuButton release];
    [openFlagImage release];
    [super dealloc];
}


- (void) setOperationStatus
{
    canTwitter = NO;
    canDM = NO;
    canMessage = NO;
    canEdit = YES;
    canDelete = YES;
    canMember = YES;
    
    for ( User* user in group.friends ) {
        if ( user.phone && [user.phone length]>0 ) {
            canMessage = YES;
        }
        if ( [kUserStateValid compare:user.state] == NSOrderedSame ) {
            canTwitter = YES;
            if ( [user.relation compare:kUserRelationBoth] == NSOrderedSame ) {
                canDM = YES;
            }
        }
        
        if ( canMessage && canTwitter && canDM ) break;
    }
    
    
    if ( group.groupId == 0 ) {
        canEdit = NO;
        canDelete = NO;
        canMember = NO;
    }
}



/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */


#pragma mark - 分组方法

- (void) expandSection
{
	UITableView* tableView = (UITableView*) self.superview;
	FriendsViewController* controller = (FriendsViewController*) tableView.delegate;
    [controller.searchBar resignFirstResponder];

	[controller sectionDidSelected:section];
}


- (void) groupDetail
{
	GuaziAppDelegate* appDelegate = [GuaziAppDelegate getAppDelegate];
	UINavigationController* nav = [appDelegate.tabBarController.viewControllers objectAtIndex:appDelegate.tabBarController.selectedIndex];

	GroupDetailViewController* controller = [[GroupDetailViewController alloc] initWithGroup:group];
	controller.hidesBottomBarWhenPushed = YES;
	[nav pushViewController:controller animated:YES];
    [controller release];
}


#pragma mark - pop menu operations

- (void) popMenu
{
	UITableView* tableView = (UITableView*) self.superview;
	FriendsViewController* controller = (FriendsViewController*) tableView.delegate;
    [controller.searchBar resignFirstResponder];
    
    if ( self.popoverController ) {
        [self.popoverController dismissPopoverAnimated:YES];
        self.popoverController = nil;
    }
    
    UIViewController* contentViewController = [[PopMenuViewController alloc] initWithContentDelegate:self];
    self.popoverController = [[[WEPopoverController alloc] initWithContentViewController:contentViewController] autorelease];
    self.popoverController.delegate = self;
    [self.popoverController presentPopoverFromRect:menuButton.frame 
                                              inView:self 
                            permittedArrowDirections:(UIPopoverArrowDirectionUp|UIPopoverArrowDirectionDown)
                                            animated:YES];
    [contentViewController release];
}


- (NSString*) popMenuTitle
{
    return @"分组操作";
}


- (NSInteger) popMenuItemCount
{
    NSInteger count = 0;
    if (canTwitter) count++;
    if (canDM) count++;
    if (canMessage) count++;
    if (canEdit) count++;
    if (canDelete) count++;
    if (canMember) count++;

    return count;
}


- (NSString*) popMenuItemName:(NSInteger)menuItem
{
    NSArray* names = [self menuItemNames];
    return [names objectAtIndex:menuItem];
}


- (void) didSelectPopMenuItem:(NSInteger)menuItem
{
    [self.popoverController dismissPopoverAnimated:YES];
    self.popoverController = nil;
    
    NSString* itemName = [self popMenuItemName:menuItem];
    if ( [kMenuItemNameTwitter compare:itemName]==NSOrderedSame ) {
        [self postTweet];
    }
    else if ( [kMenuItemNameDM compare:itemName] == NSOrderedSame ) {
        [self postDirectMessage];
    }
    else if ( [kMenuItemNameMessage compare:itemName] == NSOrderedSame ) {
        [self sendMessage];
    }
    else if ( [kMenuItemNameMember compare:itemName] == NSOrderedSame ) {
        [self member];
    }
    else if ( [kMenuItemNameEdit compare:itemName] == NSOrderedSame ) {
        [self editGroup];
    }
    else if ( [kMenuItemNameDelete compare:itemName] == NSOrderedSame ) {
        [self deleteGroup];
    }
}


- (NSArray*) menuItemNames
{
    NSMutableArray* names = [NSMutableArray array];
    if (canTwitter) {
        [names addObject:kMenuItemNameTwitter];
    }
    
    if (canDM) {
        [names addObject:kMenuItemNameDM];
    }
    
    if (canMessage) {
        [names addObject:kMenuItemNameMessage];
    }
    
    if (canMember) {
        [names addObject:kMenuItemNameMember];
    }
    
    if (canEdit) {
        [names addObject:kMenuItemNameEdit];
    }
    
    if (canDelete) {
        [names addObject:kMenuItemNameDelete];
    }
    return names;
}


#pragma mark -
#pragma mark WEPopoverControllerDelegate implementation

- (void)popoverControllerDidDismissPopover:(WEPopoverController *)thePopoverController {
	//Safe to release the popover here
	self.popoverController = nil;
}

- (BOOL)popoverControllerShouldDismissPopover:(WEPopoverController *)thePopoverController {
	//The popover is automatically dismissed if you click outside it, unless you return NO here
	return YES;
}


#pragma mark - 分组方法

//发动态
- (void) postTweet
{
    GuaziAppDelegate *appDelegate = [GuaziAppDelegate getAppDelegate];
    PostViewController* postView = appDelegate.postView;
	[postView postGroup:group];
}


//fa私信
- (void)postDirectMessage
{
    GuaziAppDelegate *appDelegate = [GuaziAppDelegate getAppDelegate];
    PostViewController* postView = appDelegate.postView;
	[postView editDirectMessageGroup:group];
}


//发短信
- (void) sendMessage
{
	NSMutableArray* array = [NSMutableArray array];;
	for ( User* user in group.friends ) {
		if ( user.phone != nil && [user.phone length] > 0 ) {
			[array addObject:user.phone];
		}
	}
	
	if ( [array count] > 0 ) {
        UIViewController* controller = [[GuaziAppDelegate getAppDelegate] currentViewController];
		MessagePicker* picker = [[MessagePicker alloc] initWithController:controller recienpts:array body:@""];
		[picker send];
		[picker release];
	}
}


//编辑组
- (void) editGroup
{
	GroupAddViewController* controller = [[GroupAddViewController alloc] init];
	controller.group = group;
    
    UINavigationController* nav = [[GuaziAppDelegate getAppDelegate] currentNavigationController];
	[nav pushViewController:controller animated:YES];
	[controller release];
}


//组内成员
- (void) member
{
    FriendGroup* g = [FriendGroup groupWithGroup:group];
	GroupUserListViewController* controller = [[GroupUserListViewController alloc] initWithGroup:g];
    UINavigationController* nav = [[GuaziAppDelegate getAppDelegate] currentNavigationController];
	[nav pushViewController:controller animated:YES];
	[controller release];
}


//删除组
- (void) deleteGroup
{
	UIActionSheet* sheet = [[UIActionSheet alloc] initWithTitle:@"删除组后，本组内的联系人将变成未分组状态。是否确认删除本组？" 
													   delegate:self 
											  cancelButtonTitle:@"取消" 
										 destructiveButtonTitle:@"确认" otherButtonTitles:nil];
	[sheet showInView:[GuaziAppDelegate getAppDelegate].tabBarController.view];
	[sheet release];
}


- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
	if ( buttonIndex == 0 ) {
        BOOL result = [GroupService deleteGroup:group.groupId];
        if ( result ) {
            FriendsViewController* controller = (FriendsViewController*) [[GuaziAppDelegate getAppDelegate] currentTabRootViewController];
            [controller refreshDeleteGroup:group];
        }
        
        UINavigationController* nav = [[GuaziAppDelegate getAppDelegate] currentNavigationController];
		[nav popViewControllerAnimated:YES];
	}
}



@end
